<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能药品仓储系统</title>
    <style>
        :root {
            --sidebar-width: 220px;
            --primary-color: #3498db;
            --hover-color: #2980b9;
            --bg-color: #f5f7fa;
            --panel-bg: #ffffff;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: var(--bg-color);
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: var(--sidebar-width);
            background-color: #2c3e50;
            color: white;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }

        .sidebar-menu li:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .sidebar-menu li.active {
            background-color: rgba(255, 255, 255, 0.2);
            border-left: 4px solid var(--primary-color);
        }

        .sidebar-menu li i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .content-panel {
            display: none;
            background-color: var(--panel-bg);
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .content-panel.active {
            display: block;
        }

        .panel-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #2c3e50;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .info-card {
            background-color: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .info-label {
            font-weight: bold;
            color: #7f8c8d;
            margin-bottom: 5px;
            font-size: 14px;
        }

        .info-value {
            font-size: 16px;
            color: #2c3e50;
        }

        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-online {
            background-color: #2ecc71;
        }

        .status-offline {
            background-color: #e74c3c;
        }

        .register-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .register-table th,
        .register-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        .register-table th {
            background-color: #f2f2f2;
            font-weight: 600;
        }

        .register-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .video-container {
            width: 100%;
            height: 400px;
            background-color: #333;
            border-radius: 6px;
            overflow: hidden;
            position: relative;
        }

        .video-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
        }

        .video-stream {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: none;
        }

        .refresh-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            margin-top: 10px;
        }

        .refresh-btn:hover {
            background-color: var(--hover-color);
        }

        .last-update {
            font-size: 12px;
            color: #95a5a6;
            margin-top: 10px;
            text-align: right;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- 中文名称映射 -->
    <script>
        const regNameMap = {
            101: '温度',
            102: '湿度',
            103: '火焰传感器',
            104: '红外传感器',
            105: '照明',
            106: '水泵',
            107: '风扇',
            108: '蜂鸣器',
            109: '冷凝片',
        };
    </script>
</head>

<body>
    <!-- 侧边导航栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h2>监控系统</h2>
            <p>v1.0.0</p>
        </div>
        <ul class="sidebar-menu">
            <li data-panel="gateway"><i class="fas fa-server"></i>网关设备</li>
            <li class="active" data-panel="registers"><i class="fas fa-microchip"></i>寄存器状态</li>
            <li data-panel="drug"><i class="fas fa-pills"></i>药品管理</li>
            <li data-panel="video"><i class="fas fa-video"></i>视频监控</li>
            <li data-panel="settings"><i class="fas fa-cog"></i>系统设置</li>
        </ul>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 网关设备面板 -->
        <div class="content-panel" id="gateway-panel">
            <div class="panel-title">网关设备信息</div>
            <div class="info-grid">
                <div class="info-card">
                    <div class="info-label">主机名</div>
                    <div class="info-value">Gateway-001</div>
                </div>
                <div class="info-card">
                    <div class="info-label">固件版本</div>
                    <div class="info-value">v1.0</div>
                </div>
                <div class="info-card">
                    <div class="info-label">系统运行时间</div>
                    <div class="info-value">3天12小时45分</div>
                </div>
                <div class="info-card">
                    <div class="info-label">IP地址</div>
                    <div class="info-value">192.168.1.100</div>
                </div>
                <div class="info-card">
                    <div class="info-label">内存使用</div>
                    <div class="info-value">256MB/512MB (50%)</div>
                </div>
                <div class="info-card">
                    <div class="info-label">CPU使用率</div>
                    <div class="info-value">25%</div>
                </div>
                <div class="info-card">
                    <div class="info-label">MQTT服务器</div>
                    <div class="info-value">192.168.50.60:1883</div>
                </div>
                <div class="info-card">
                    <div class="info-label">报告周期</div>
                    <div class="info-value">5秒</div>
                </div>
            </div>
            <button class="refresh-btn" onclick="fetchGatewayInfo()"><i class="fas fa-sync-alt"></i> 刷新数据</button>
            <div class="last-update" id="gateway-last-update">最后更新: 刚刚</div>
        </div>

        <!-- 寄存器状态面板-->
        <div class="content-panel active" id="registers-panel">
            <div class="panel-title">单片机寄存器状态</div>
            <table class="register-table">
                <thead>
                    <tr>
                        <th>键值</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>值</th>
                        <th>控制</th>
                    </tr>
                </thead>
                <tbody id="stm32-registers"></tbody>
            </table>
            <div class="panel-title" style="margin-top: 30px;">Modbus Slave寄存器</div>
            <table class="register-table">
                <thead>
                    <tr>
                        <th>键值</th>
                        <th>名称</th>
                        <th>地址</th>
                        <th>类型</th>
                        <th>值</th>
                        <th>控制</th>
                    </tr>
                </thead>
                <tbody id="modbus-registers"></tbody>
            </table>
            <div class="last-update" id="registers-last-update">--</div>
            <button class="refresh-btn" onclick="setManualMode()" style="margin-top:10px;">切换手动模式</button>
            <button class="refresh-btn" onclick="setAutoMode()" style="margin-left:10px;">切换自动模式</button>
        </div>
        <!-- 药品管理面板 -->
        <div class="content-panel" id="drug-panel">
            <div class="panel-title"><i class="fas fa-pills"></i>药品存取及查看</div>

            <!-- 存药 -->
            <div class="info-card" style="margin-bottom:20px;">
                <div class="info-label">存药</div>
                <input type="text" id="drug-name" placeholder="药品名称" list="drug-history" style="width:150px;margin-right:10px;">
                <input type="number" id="drug-count" placeholder="数量" style="width:80px;margin-right:10px;">
                <button class="refresh-btn" onclick="saveDrug()">存入</button>
                <datalist id="drug-history"></datalist>
            </div>

            <!-- 取药 -->
            <div class="info-card" style="margin-bottom:20px;">
                <div class="info-label">取药</div>
                <input type="text" id="take-name" placeholder="药品名称" list="drug-history" style="width:150px;margin-right:10px;">
                <input type="number" id="take-count" placeholder="数量" style="width:80px;margin-right:10px;">
                <button class="refresh-btn" onclick="takeDrug()">取出</button>
                <datalist id="drug-history"></datalist>
            </div>

            <!-- 药品库存表 -->
            <div class="panel-title">药品库存</div>
            <table class="register-table" id="drug-table">
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>库存</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <button class="refresh-btn" onclick="loadDrugList()" style="margin-top:10px;">刷新库存</button>
        </div>
        <!-- 视频监控面板 -->
        <div class="content-panel" id="video-panel">
            <div class="panel-title">实时视频监控</div>
            <img id="mjpeg-stream" src="http://192.168.50.236:8080/?action=stream"
                style="width:100%;height:400px;object-fit:contain;background:#000;"
                onload="this.style.display='block';document.getElementById('video-placeholder') && (document.getElementById('video-placeholder').style.display='none');"
                onerror="this.style.display='none';document.getElementById('video-placeholder') && (document.getElementById('video-placeholder').style.display='flex');">
            <div class="video-placeholder" id="video-placeholder" style="display:none;">
                正在连接视频流...
            </div>

            <!-- 视频信息放回视频面板 -->
            <div style="margin-top: 20px;">
                <div class="info-grid">
                    <div class="info-card">
                        <div class="info-label">视频流地址</div>
                        <div class="info-value" id="video-stream-url">http://192.168.50.236:8080/?action=stream</div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">视频状态</div>
                        <div class="info-value"><span class="status-indicator status-online" id="video-status"></span>加载中...
                        </div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">帧率</div>
                        <div class="info-value" id="video-fps">N/A</div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">分辨率</div>
                        <div class="info-value" id="video-resolution">实时</div>
                    </div>
                </div>
            </div>

            <button class="refresh-btn" onclick="document.getElementById('mjpeg-stream').src += '?t=' + Date.now()">
                <i class="fas fa-sync-alt"></i> 重新连接
            </button>
            <div class="last-update" id="video-last-update">最后更新: 刚刚</div>
        </div>

        <!-- 系统设置面板 -->
        <div class="content-panel" id="settings-panel">
            <div class="panel-title">系统设置</div>
            <div class="info-card" style="max-width: 600px;">
                <div class="info-label">MQTT服务器配置</div>
                <div style="margin-top: 15px;">
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">服务器地址:</label>
                        <input type="text" id="mqtt-addr" value="192.168.50.60"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">端口:</label>
                        <input type="text" id="mqtt-port" value="1883"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                </div>

                <div class="info-label" style="margin-top: 20px;">Modbus配置</div>
                <div style="margin-top: 15px;">
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">设备地址:</label>
                        <input type="text" id="modbus-dev-addr" value="192.168.x.x"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">端口:</label>
                        <input type="text" id="modbus-dev-port" value="502"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                </div>

                <div class="info-label" style="margin-top: 20px;">视频流配置</div>
                <div style="margin-top: 15px;">
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">视频流地址:</label>
                        <input type="text" id="video-stream-addr" value="192.168.xx.xx"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                    <div style="display: flex; align-items: center; margin-bottom: 10px;">
                        <label style="width: 120px;">端口:</label>
                        <input type="text" id="video-stream-port" value="8887"
                            style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    </div>
                </div>

                <button class="refresh-btn" style="margin-top: 20px;" onclick="saveSettings()">
                    <i class="fas fa-save"></i> 保存设置
                </button>
            </div>
        </div>
    </div>

    <script>
        /* 面板切换（原版） */
        document.querySelectorAll('.sidebar-menu li').forEach(item => {
            item.addEventListener('click', function () {
                document.querySelectorAll('.sidebar-menu li').forEach(li => li.classList.remove('active'));
                this.classList.add('active');
                document.querySelectorAll('.content-panel').forEach(panel => panel.classList.remove('active'));
                document.getElementById(this.dataset.panel + '-panel').classList.add('active');
            });
        });

        /* 网关信息模拟刷新（原版） */
        function fetchGatewayInfo() {
            const now = new Date();
            const memoryUsed = 200 + Math.random() * 100;
            const totalMem = 512;
            const memPercent = (memoryUsed / totalMem * 100).toFixed(0);
            const cpuUsage = (10 + Math.random() * 30).toFixed(0);
            document.getElementById('memory-usage').textContent = `${Math.floor(memoryUsed)}MB/${totalMem}MB (${memPercent}%)`;
            document.getElementById('cpu-usage').textContent = `${cpuUsage}%`;
            document.getElementById('gateway-last-update').textContent = `最后更新: ${now.toLocaleTimeString()}`;
        }

        function fetchRegisterData() {
            fetch('/?get=nodes')
                .then(res => res.json())
                .then(data => {
                    const stm32Tbody = document.getElementById('stm32-registers');
                    const modbusTbody = document.getElementById('modbus-registers');
                    stm32Tbody.innerHTML = '';
                    modbusTbody.innerHTML = '';

                    data.forEach(node => {
                        const name = regNameMap[node.key] || node.key;
                        let valueStr = node.type === 3
                            ? node.value.toFixed(1) + (node.key === 101 ? '°C' : '')
                            : (parseInt(node.value) ? '开' : '关');

                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                    <td>${node.key}</td>
                    <td>${name}</td>
                    <td>${node.type}</td>
                    <td>${valueStr}</td>`;

                        /* ① 按钮列：根据 key 范围决定队列名 */
                        const btn = document.createElement('td');
                        if (node.key >= 101 && node.key <= 110) {
                            // 隐藏101-104的按钮
                            if (node.key < 101 || node.key > 104) {
                                btn.innerHTML = `
                            <button onclick="sendCommand('stm32',${node.key},1)">开</button>
                            <button onclick="sendCommand('stm32',${node.key},0)">关</button>`;
                            }
                            stm32Tbody.appendChild(tr);
                        } else if (node.key >= 201 && node.key <= 299) {
                            btn.innerHTML = `
                        <button onclick="sendCommand('modbus',${node.key},1)">开</button>
                        <button onclick="sendCommand('modbus',${node.key},0)">关</button>`;
                            const addrTd = document.createElement('td');
                            addrTd.textContent = node.addr || '1';
                            tr.insertBefore(addrTd, tr.children[2]);
                            modbusTbody.appendChild(tr);
                        }
                        tr.appendChild(btn);
                    });
                    document.getElementById('registers-last-update').textContent =
                        `最后更新: ${new Date().toLocaleTimeString()}`;
                })
                .catch(console.error);
        }

        /* 视频流模拟（原版） */
        function connectVideoStream() {
            const placeholder = document.getElementById('video-placeholder');
            const video = document.getElementById('video-stream');
            placeholder.style.display = 'flex';
            video.style.display = 'none';
            setTimeout(() => {
                placeholder.textContent = "视频流连接成功";
                const now = new Date();
                document.getElementById('video-last-update').textContent = `最后更新: ${now.toLocaleTimeString()}`;
                document.getElementById('video-fps').textContent = `${Math.floor(15 + Math.random() * 10)} FPS`;
            }, 1000);
        }

        /* 首次加载 & 循环刷新 */
        document.addEventListener('DOMContentLoaded', () => {
            fetchRegisterData();        // 立即拉一次寄存器
            setInterval(fetchRegisterData, 5000); // 每 5 秒
            fetchGatewayInfo();
            setInterval(fetchGatewayInfo, 10000);
            connectVideoStream();
        });

        function sendCommand(type, key, val) {
            fetch(`/?control=${type}&key=${key}&val=${val}`)
                .then(r => r.json())
                .then(d => console.log('下发成功', d))
                .catch(console.error);
        }
        // 切换 STM32 控制模式（自动/手动）
        function setManualMode() {
            fetch('/?control=stm32&key=501&val=1')
                .then(r => alert('已设为手动'));
        }

        // 自动模式
        function setAutoMode() {
            fetch('/?control=stm32&key=501&val=0')
                .then(r => alert('已设为自动'));
        }

        /* 药品管理本地演示 + 输入清空 + 历史记录 */
        let drugDB = JSON.parse(localStorage.getItem('drugs') || '{}');
        let drugHistory = JSON.parse(localStorage.getItem('drugHistory') || '[]');

        function refreshDrugHistory() {
            const list = document.getElementById('drug-history');
            list.innerHTML = '';
            drugHistory.forEach(name => {
                const opt = document.createElement('option');
                opt.value = name;
                list.appendChild(opt);
            });
        }

        function saveDrug() {
            const name = document.getElementById('drug-name').value.trim();
            const cnt = parseInt(document.getElementById('drug-count').value) || 0;
            if (!name || cnt <= 0) return alert('请输入药品名和正整数');
            drugDB[name] = (drugDB[name] || 0) + cnt;
            localStorage.setItem('drugs', JSON.stringify(drugDB));
            // 维护历史
            if (!drugHistory.includes(name)) drugHistory.unshift(name);
            drugHistory = drugHistory.slice(0, 20); // 最多保留20条
            localStorage.setItem('drugHistory', JSON.stringify(drugHistory));
            document.getElementById('drug-name').value = '';
            document.getElementById('drug-count').value = '';
            refreshDrugHistory();
            alert('存入成功');
            loadDrugList();
        }

        function takeDrug() {
            const name = document.getElementById('take-name').value.trim();
            const cnt = parseInt(document.getElementById('take-count').value) || 0;
            if (!name || cnt <= 0) return alert('请输入药品名和正整数');
            if (!drugDB[name] || drugDB[name] < cnt) return alert('库存不足');
            drugDB[name] -= cnt;
            if (drugDB[name] === 0) delete drugDB[name];
            localStorage.setItem('drugs', JSON.stringify(drugDB));
            document.getElementById('take-name').value = '';
            document.getElementById('take-count').value = '';
            alert('取出成功');
            loadDrugList();
        }

        function loadDrugList() {
            const tbody = document.querySelector('#drug-table tbody');
            tbody.innerHTML = '';
            for (const [n, q] of Object.entries(drugDB)) {
                tbody.innerHTML += `<tr><td>${n}</td><td>${q}</td></tr>`;
            }
        }
        document.addEventListener('DOMContentLoaded', () => {
            loadDrugList();
            refreshDrugHistory();
        });
    </script>
</body>

</html>